// API 请求工具：统一封装 fetch，自动拼接 BASE、携带 X-User-Id 头、统一错误处理
// 使用方式：
//   import { api } from '@/utils/api'
//   await api.get('/user/list', { page: 1 })
//   await api.post('/worklog/add', { title: '...' })
// 说明：
//   - BASE 从环境变量 VITE_API_BASE 读取；若未配置，默认同源
//   - 在登录后会将 userId 存在 localStorage，用于向后端透传 X-User-Id（当前简化鉴权方案）
//   - 仅当响应 content-type 为 application/json 时自动做 JSON 解析，否则按文本返回
const BASE = import.meta.env.VITE_API_BASE || ''
const DEV = import.meta.env.DEV

/**
 * 发起 HTTP 请求
 * @param {string} path 相对路径，如 '/user/list'
 * @param {object} options 可选项：{ method, params, body }
 *  - method: GET/POST/PUT/DELETE，默认 GET
 *  - params: 查询参数对象，会追加到 URL 上
 *  - body:   请求体对象，会以 JSON 序列化发送
 */
async function request(path, { method = 'GET', params, body } = {}) {
  const url = new URL(path, BASE || window.location.origin)
  if (params && typeof params === 'object') {
    Object.entries(params).forEach(([k, v]) => v != null && url.searchParams.set(k, v))
  }
  const headers = { 'Content-Type': 'application/json' }
  const uid = localStorage.getItem('userId')
  if (uid) headers['X-User-Id'] = String(uid)

  const finalUrl = url.toString()
  if (DEV) console.debug('[api]', method, finalUrl, body || params || '')
  const res = await fetch(finalUrl, {
    method,
    headers,
    body: body != null ? JSON.stringify(body) : undefined,
    credentials: 'include'
  })
  if (!res.ok) {
    const txt = await res.text().catch(() => '')
    if (DEV) console.error('[api-error]', method, finalUrl, res.status, txt)
    throw new Error(`${res.status} ${txt || res.statusText}`)
  }
  const ct = res.headers.get('content-type') || ''
  if (ct.includes('application/json')) return res.json()
  return res.text()
}

export const api = {
  get: (path, params) => request(path, { method: 'GET', params }),
  post: (path, body) => request(path, { method: 'POST', body }),
  put: (path, body) => request(path, { method: 'PUT', body }),
  del: (path, params) => request(path, { method: 'DELETE', params }),
  /**
   * 以 application/x-www-form-urlencoded 发送表单
   * @param {string} path
   * @param {Record<string, any>} form
   */
  postForm: async (path, form) => {
    const url = new URL(path, BASE || window.location.origin)
    const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
    const uid = localStorage.getItem('userId')
    if (uid) headers['X-User-Id'] = String(uid)
    const body = new URLSearchParams()
    Object.entries(form || {}).forEach(([k, v]) => body.append(k, v == null ? '' : String(v)))
    const finalUrl = url.toString()
    if (DEV) console.debug('[api]', 'POST(FORM)', finalUrl, form)
    const res = await fetch(finalUrl, { method: 'POST', headers, body, credentials: 'include' })
    if (!res.ok) {
      const txt = await res.text().catch(() => '')
      if (DEV) console.error('[api-error]', 'POST(FORM)', finalUrl, res.status, txt)
      throw new Error(`${res.status} ${txt || res.statusText}`)
    }
    const ct = res.headers.get('content-type') || ''
    if (ct.includes('application/json')) return res.json()
    return res.text()
  }
}
